package com.example.demo.service.impl;

import com.example.demo.entity.Like;
import com.example.demo.entity.Post;
import com.example.demo.mapper.LikeMapper;
import com.example.demo.mapper.PostMapper;
import com.example.demo.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private LikeMapper likeMapper;

    @Override
    @Transactional
    public Post createPost(Post post) {
        postMapper.insertPost(post);
        return postMapper.selectPostById(post.getPostId());
    }

    @Override
    public Post getPostById(Long postId) {
        return postMapper.selectPostById(postId);
    }

    @Override
    public List<Post> getPostsByAuthorId(Long authorId) {
        return postMapper.selectPostsByAuthorId(authorId);
    }

    @Override
    public List<Post> getAllPosts() {
        return postMapper.selectAllPosts();
    }

    @Override
    @Transactional
    public Post updatePost(Post post) {
        postMapper.updatePost(post);
        return postMapper.selectPostById(post.getPostId());
    }

    @Override
    @Transactional
    public void deletePost(Long postId) {
        postMapper.deletePost(postId);
    }

    @Override
    @Transactional
    public void likePost(Long userId, Long postId) {
        if (likeMapper.selectLikeByUserAndPost(userId, postId) != null) {
            throw new RuntimeException("Already liked");
        }

        Like like = new Like(userId, postId, null);
        likeMapper.insertLike(like);
        postMapper.incrementLikeCount(postId);
    }

    @Override
    @Transactional
    public void unlikePost(Long userId, Long postId) {
        if (likeMapper.selectLikeByUserAndPost(userId, postId) == null) {
            throw new RuntimeException("Not liked yet");
        }

        likeMapper.deleteLikeByUserAndPost(userId, postId);
        postMapper.decrementLikeCount(postId);
    }
}